<template>
  <Echart id="leftCenter" :options="options" class="left_center_inner" v-if="pageflag" ref="charts"/>
  <Reacquire v-else @onclick="getData" style="line-height:200px">{{ $t('bigScreen.reacquire') }}</Reacquire>
</template>
<script>
import { listDeviceUser1, listDeviceUsers } from '@/api/iot/lightpole'
export default {
  data() {
    return {
      options: {},
      countData: {
        total: 0,
        devicesOn: 0,
        onlineScreens: 0,
        devicesOff: 0,
        offlineScreens: 0,
      },
      pageflag: true,
      timer: null
    };
  },
  filters: {
    numsFilter(msg) {
      return msg || 0;
    },
  },
  created() {
    this.getData()
  },
  beforeDestroy() {
    this.clearData()
  },
  methods: {
    clearData() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null
      }
    },
    getData() {
      this.pageflag = true
      listDeviceUsers().then(res => {
        console.log("res", res);
        if (res.code == 0) {
          const rows = res.rows;
          if (rows && rows.length > 0 && rows[0]) {
            this.countData = res.rows[0]
            this.$nextTick(() => {
              this.init();
              this.switper()
            })
          } else {
            this.pageflag = false
            this.$message({text: this.$t('bigScreen.emptyData'), type: 'warning'})
          }
        } else {
          this.pageflag = false
          this.$message({text: res.msg || this.$t('bigScreen.dataFailed'), type: 'warning'})
        }
      })
    },
    switper() {
      if (this.timer) {
        return
      }
      let looper = (a) => {};
      const autoTime = this.$store.state.settings.echartsAutoTime;
      this.timer = setInterval(looper, autoTime);
      let myChart = this.$refs.charts.chart;
      myChart.on('mouseover', params => {
        this.clearData()
      });
      myChart.on('mouseout', params => {
        if (!this.timer) {
          this.timer = setInterval(looper, autoTime);
        }
      });
    },
    init() {
      // 定义颜色
      const colors = ["#ECA444", "#33A1DB", "#56B557", "#1016ff", "#dbff00", "#00a395"];
      // 计算总数
      const total = this.countData.total || 1; // 避免除零错误
      // 准备数据
      const categories = [
        this.$t('bigScreen.screenOnline'),
        this.$t('bigScreen.screenOffline'),
        this.$t('bigScreen.poleOnline'),
        this.$t('bigScreen.poleOffline')
      ];
      const seriesData = [
        {
          name: this.$t('bigScreen.screenOnline'),
          value: this.countData.onlineScreens,
          percent: ((this.countData.onlineScreens / total) * 100).toFixed(1) + '%',
          itemStyle: { color: colors[3] }
        },
        {
          name: this.$t('bigScreen.screenOffline'),
          value: this.countData.offlineScreens,
          percent: ((this.countData.offlineScreens / total) * 100).toFixed(1) + '%',
          itemStyle: { color: colors[4] }
        },
        {
          name: this.$t('bigScreen.poleOnline'),
          value: this.countData.devicesOn,
          percent: ((this.countData.devicesOn / total) * 100).toFixed(1) + '%',
          itemStyle: { color: colors[2] }
        },
        {
          name: this.$t('bigScreen.poleOffline'),
          value: this.countData.devicesOff,
          percent: ((this.countData.devicesOff / total) * 100).toFixed(1) + '%',
          itemStyle: { color: colors[5] }
        }
      ];
      this.options = {
        title: {
          text: `${this.$t('bigScreen.totalDevices')}: ${this.countData.total}`,
          top: "top",
          left: "center",
          textStyle: {
            color: "#ffffff",
            fontSize: 18,
            fontWeight: "bold"
          },
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            const data = params[0].data;
            return `${data.name}<br/>${this.$t('bigScreen.quantity')}: ${data.value}<br/>${this.$t('bigScreen.proportion')}: ${data.percent}`;
          }.bind(this),
          backgroundColor: "rgba(0,0,0,.6)",
          borderColor: "rgba(147,235,248,.8)",
          textStyle: { color: "#FFF" }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: categories,
          axisLabel: {
            color: '#fff',
            rotate: 30
          },
          axisLine: {
            lineStyle: {
              color: '#fff'
            }
          }
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: function(value) {
            return Math.ceil(value.max);
          },
          axisLabel: {
            color: '#fff',
            fontSize: 12,
            show: true
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#fff'
            }
          },
          axisTick: {
            show: true
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.2)'
            }
          }
        },
        series: [
          {
            name: this.$t('bigScreen.deviceQuantity'),
            type: 'bar',
            barWidth: '40%',
            data: seriesData,
            itemStyle: {
              color: function(params) {
                return seriesData[params.dataIndex].itemStyle.color;
              }
            },
            label: {
              show: true,
              position: 'top',
              color: '#fff',
              formatter: function(params) {
                return `${params.data.value}\n(${params.data.percent})`;
              }
            }
          }
        ]
      };
    }
  }
};
</script>
<style lang='scss' scoped></style>
